package com.fate.system.utils;

import com.aspose.words.Document;
import com.aspose.words.NodeCollection;
import com.aspose.words.NodeType;
import com.aspose.words.Shape;
import com.fate.framework.utils.CommonUtil;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;

public class CompressWord {
  public static void compress(Document document) throws Exception {
    // 清理文档以删除空白段落等
    document.cleanup();

    // 获取文档中所有的Shape节点
    NodeCollection nodes = document.getChildNodes(NodeType.SHAPE, true);
    for (Shape shape : (Iterable<Shape>) nodes) {
      if (shape.hasImage()) {
        // 读取图像数据为BufferedImage
        BufferedImage image = ImageIO.read(shape.getImageData().toStream());

        // 压缩图像
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
        writer.setOutput(ios);

        ImageWriteParam param = writer.getDefaultWriteParam();
        if (param.canWriteCompressed()) {
          param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
          param.setCompressionQuality(0.5f); // 压缩质量，0.5表示50%的质量
        }

        if (CommonUtil.isNullOrEmpty(image)) {
          continue;
        }

        writer.write(null, new javax.imageio.IIOImage(image, null, null), param);

        ios.close();
        writer.dispose();

        // 将压缩后的图像重新设置回Shape
        ByteArrayInputStream compressedImageStream = new ByteArrayInputStream(baos.toByteArray());
        shape.getImageData().setImage(compressedImageStream);
      }
    }
  }
}
